using System;
using System.Windows;
using System.Windows.Forms;
using Microsoft.Practices.Composite.Events;
using uTorrentNetClient.ModelDesign.Contracts;
using uTorrentNetClient.ModelDesign.Events;
using uTorrentNetClient.ModelDesign.Properties;

namespace uTorrentNetClient.ModelDesign.Notify
{
    public class Notify : INotify
    {
        private WindowState _pState;
        private NotifyIcon _nIcon;

        public Notify(IEventAggregator eventAggregator)
        {
            _nIcon = new NotifyIcon();
            _nIcon.Icon = Resources.TheFatController;
            _nIcon.Visible = true;
            _nIcon.DoubleClick += _nIcon_DoubleClick;
            _pState = WindowState.Normal;
            _nIcon.ContextMenu = new ContextMenu();
            _nIcon.ContextMenu.MenuItems.Add("Anzeigen", showApp);
            _nIcon.ContextMenu.MenuItems.Add("Beenden", closeApp);

            eventAggregator.GetEvent<ChangeWindowStateEvent>().Subscribe(changeWindowStateEventExecute);
            eventAggregator.GetEvent<ShowBalloonTipEvent>().Subscribe(showBalloonTipEventExecute);
            eventAggregator.GetEvent<UpdateNotifyToolTipInfoEvent>().Subscribe(updateToolTipInfo);
        }

        private void showApp(object sender, EventArgs e)
        {
            if (ShellView != null && ShellView.WindowState == WindowState.Minimized)
                ShellView.WindowState = _pState;
        }

        private void closeApp(object sender, EventArgs e)
        {
            if(ShellView != null)
                ShellView.CloseView();
        }

        private void updateToolTipInfo(string obj)
        {
            _nIcon.Text = obj;
        }

        private void showBalloonTipEventExecute(string obj)
        {
            if(ShellView != null && ShellView.WindowState == WindowState.Minimized)
                _nIcon.ShowBalloonTip(4000, "uTorrent-Net Client", obj, ToolTipIcon.Info);
        }

        private void changeWindowStateEventExecute(WindowState obj)
        {
            if (_pState != obj && obj != WindowState.Minimized)
                _pState = obj;
        }

        void _nIcon_DoubleClick(object sender, System.EventArgs e)
        {
            if (ShellView != null && ShellView.WindowState == WindowState.Minimized)
                ShellView.WindowState = _pState;
        }

        public IShellView ShellView { get; set; }
        public void CloseIcon()
        {
            _nIcon.Visible = false;
            _nIcon.Dispose();
        }
    }
}